//
//  BackGroundTaskView.m
//  CoreBlueTooth
//
//  Created by bodyconn on 15/2/2.
//  Copyright (c) 2015年 bodyconn. All rights reserved.
//

#import "BackGroundTaskView.h"
#import "HDAlertView.h"
#define STOREAPPID @"1220320569"
@implementation BackGroundTaskView

DEF_SINGLETON(BackGroundTaskView)
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */
- (instancetype)init {
    self = [super init];
    if (self) {
        _isBackGroundTask = YES;
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(BecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(Bebackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    }
    return self;
}

- (void)updateNewVersion:(NSDictionary *)dic {
    NSString *currentVersion      = APP_CURRENTVERSION;
    NSString *appStoreVersion     = dic[@"version_code"];
    NSString *appStoreVersionShow = dic[@"version_name"];
    
    SN_USER.lastOnlineAppVersion = appStoreVersionShow;
    NSString *appVersion   = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
    NSString *storeVersion = appStoreVersion;
    if ([appVersion floatValue] < [storeVersion floatValue]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:SN_Text(@"版本有更新") message:[NSString stringWithFormat:@"%@(%@),%@", SN_Text(@"检测到新版本"), appStoreVersionShow, SN_Text(@"是否更新?")] delegate:self cancelButtonTitle:SN_Text(@"取消") otherButtonTitles:SN_Text(@"更新"), nil];
        [alert show];
    } else {
        NSLog(@"版本号好像比商店大噢!检测到不需要更新");
    }
}

- (void)checkAppVersionUpdate {
    NSString *getAppBuildId = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
    
    if ([getAppBuildId isEqualToString:@"com.xianweiyun.getfit3"] || [getAppBuildId isEqualToString:@"com.xianwei.fitnow"] || [getAppBuildId isEqualToString:@"com.lezhifit"]) {
        NSString *currentVersion = APP_CURRENTVERSION;
        SN_USER.lastOnlineAppVersion = currentVersion;
        [SN_Net getAppUpdateInfoFromServerWithSuccess:^(id object) {
            NSDictionary *dic = object;
            [self updateNewVersion:dic];
        } fail:^(id object) {
        }];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    //5实现跳转到应用商店进行更新
    if (buttonIndex == 1) {
        if ([APP_NAME isEqualToString:@"GetFitPro"]) {
            NSString *urlString = [NSString stringWithFormat:@"https://itunes.apple.com/cn/app/getfitpro/id1220320569?mt=8"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
        } else if ([APP_NAME isEqualToString:@"WellGo"]) {
            NSString *urlString = [NSString stringWithFormat:@"https://itunes.apple.com/cn/app/wellgo/id1304109221?mt=8"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
        } else {
        }
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"BecomeActive" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"Bebackground" object:nil];
}

#pragma mark --- 应用切换到后台模式 ---
- (void)Bebackground:(NSNotification *)Info {
    _isBackTast = YES;
    UIApplication *app = [UIApplication sharedApplication];
    
    self.bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:self.bgTask];
        self.bgTask = UIBackgroundTaskInvalid;
    }];
    
    _backTaskModeTimer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(applyForMoreTime) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop]addTimer:_backTaskModeTimer forMode:NSRunLoopCommonModes];
}

- (void)applyForMoreTime {
    // 后台进行重连接
    if (_isBackGroundTask) {
    }
    
    if ([UIApplication sharedApplication].backgroundTimeRemaining < 120) {
        [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
        self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
            self.bgTask = UIBackgroundTaskInvalid;
        }];
    }
    
    _runcount      += 30;
    _runTotalCount += 30;
    if (_runcount > 60) {
        if (!KK_BLESend.isSend) {
            _runcount = 0;
            [self getRealStep];
        }
    }
    
//    [kK_App latestRealSportDataNotification:@"applyForMoreTime定时器" subtitle:[NSString stringWithFormat:@"同步大数据( %d )",_runcount] identifier:[[NSString stringWithFormat:@"SynchronousBigData"] stringByAppendingString:[NSString stringWithFormat:@"(%d)",_runcount]]];
    
    
    //     NSLog(@"后台运行总时间>>>%d 运行间隔>>>%d",_RunTotalCount,_Runcount);
}

// 定时发送心跳包给蓝牙 获取实时步数
- (void)getRealStep {
    NSLog(@"后台续时请求");
    [KK_BLESend sendGetRealStepWithUpdate:^(id object, KKBLEAcceptType type) {
    }];
}

- (void)getDeviceInfo {
    [KK_BLESend sendGetDeviceBasicInfoWithUpdate:^(id object, KKBLEAcceptType type) {
    }];
}

#pragma mark --- 应用切换到前台模式 ---
- (void)BecomeActive:(NSNotification *)Info {
    if (_backTaskModeTimer) {
        [_backTaskModeTimer invalidate];
        _backTaskModeTimer = nil;
        _runcount          = 0;
        _runTotalCount     = 0;
    }
}

@end

